import "./index.scss";
import { useEffect, useRef } from "react";
import ElasticSlider from "../reactBits/elasticSlider";
import { v4 as uuidv4 } from "uuid";
import { Volume2, Maximize, Fullscreen, VolumeX } from "lucide-react";
import { useState } from "react";
import _ from "lodash";
import { debounce } from "@/utils/base";

const NHVideo = ({
  id = uuidv4(),
  url = "",
  width = 690,
  height = 360,
  autoPlay = false,
  border = null,
  radius = 0,
  shadow = null,
  defaultVolume = 50,
  control = null,
  onVolumeChange = () => {},
}) => {
  // is full screen
  const [isFullScreen, setIsFullScreen] = useState(false);

  // is video play
  const [isVideoPlay, setIsVideoPlay] = useState(false);

  const audioRef = useRef(null); // 用于控制音频播放的ref

  // effect
  useEffect(() => {
    // 定义隐藏超时时间（1秒）
    let timeout = 1000;
    let timer = null;

    /* 监听鼠标位置 */
    document.addEventListener("mousemove", function (event) {
      // 鼠标光标恢复默认
      document.body.style.cursor = "auto";

      let videoRect = audioRef.current.getBoundingClientRect();
      let videoMinX = videoRect.left + window.scrollX;
      let videoMaxX =
        videoRect.left + window.scrollX + audioRef.current.offsetWidth;
      let videoMinY = videoRect.top + window.scrollY;
      let videoMaxY =
        videoRect.top + window.scrollY + audioRef.current.offsetHeight;
      let mouseX = event.clientX;
      let mouseY = event.clientY;

      // 根据鼠标位置判断是否悬停在video上
      if (
        mouseX >= videoMinX &&
        mouseX <= videoMaxX &&
        mouseY >= videoMinY &&
        mouseY <= videoMaxY
      ) {
        showControl();
      } else {
        hiddenControl();
      }

      // 重置定时器
      clearTimeout(timer);
      // 重新设置3秒后执行操作
      timer = setTimeout(function () {
        document.body.style.cursor = "none";
        hiddenControl();
      }, timeout);
    });

    document.addEventListener("fullscreenchange", function (event) {
      let wrapEl = document.getElementById(`nh_video_wrap_${id}`);
      if (!document.fullscreenElement) {
        // 设置video宽高复原
        audioRef.current.style.width = width + "px";
        audioRef.current.style.height = height + "px";
        wrapEl.style.borderRadius = radius + "px";
        setIsFullScreen(false);
      }
    });

    console.log("#是否自动播放：", autoPlay ? "是" : "否");

    setTimeout(() => {
      console.log(audioRef.current && autoPlay);

      if (audioRef.current && autoPlay) {
        // 设置音频静音，浏览器允许自动播放
        audioRef.current
          .play()
          .then(() => {
            console.log("#成功");

            // 自动播放成功后取消静音
            audioRef.current.muted = false;
            setIsVideoPlay(true);
          })
          .catch((error) => {
            console.log("自动播放失败", error);
          });
      }
    }, 1000);
  }, []);

  // 显示控件
  const showControl = () => {
    let controlEl;
    document.getElementById(id).parentNode.childNodes.forEach((node) => {
      if (node.className.includes("nh_video_control_wrap")) {
        controlEl = node;
      }
    });
    controlEl.style.zIndex = "2";
    controlEl.style.bottom = "0px";
  };

  // 隐藏控件
  const hiddenControl = () => {
    let controlEl;
    document.getElementById(id).parentNode.childNodes.forEach((node) => {
      if (node.className.includes("nh_video_control_wrap")) {
        controlEl = node;
      }
    });

    controlEl.style.zIndex = "-2";
    controlEl.style.bottom = "-50px";
  };

  // 全屏按钮点击事件
  const toggleFullScreen = () => {
    let wrapEl = document.getElementById(`nh_video_wrap_${id}`);

    // 判断是进入全屏还是退出全屏
    if (isFullScreen) {
      document.exitFullscreen();

      // 设置video宽高复原
      audioRef.current.style.width = width + "px";
      audioRef.current.style.height = height + "px";
      wrapEl.style.borderRadius = radius + "px";
    } else {
      wrapEl.requestFullscreen();

      // 设置video宽高撑满
      audioRef.current.style.height = "100vh";
      audioRef.current.style.width = "100vw";
      wrapEl.style.borderRadius = "0px";
    }
    setIsFullScreen(!isFullScreen);
  };

  // 播放器点击计数
  let videoClickTimes = 0; //计时器时间内，点击次数
  // 播放器点击倒计时
  let videoClickTimer = null; //计时器

  // 播放器点击处理
  const videoHandleClick = () => {
    videoClickTimes++;
    if (videoClickTimer) return;
    videoClickTimer = setTimeout(() => {
      if (videoClickTimes === 1) {
        videoClick();
      } else {
        toggleFullScreen();
      }
      videoClickTimes = 0;
      clearTimeout(videoClickTimer);
      videoClickTimer = null;
    }, 200);
  };

  // 单击播放器画布
  const videoClick = () => {
    if (isVideoPlay) {
      videoStopPlay();
    } else {
      videoPlay();
    }
  };

  // 音量值change事件
  const volumeChange = _.debounce((value) => {
    // 回调传值
    onVolumeChange(value);

    // 设置音量值
    audioRef.current.volume = value / 100;
  }, 300);

  // 静音点击事件
  const muteClick = () => {
    // 回调传值
    onVolumeChange(80);
  };

  // 播放
  const videoPlay = () => {
    audioRef.current.muted = false; // 如果需要声音，可以在此取消静音
    audioRef.current.play();
    console.log("#开始播放");
    setIsVideoPlay(true);
  };

  // 暂停
  const videoStopPlay = () => {
    audioRef.current.pause();
    setIsVideoPlay(false);
  };

  return (
    <>
      <div
        className={`nh_video_wrap`}
        id={`nh_video_wrap_${id}`}
        style={{
          width: width,
          height: height,
          border: border,
          borderRadius: radius,
          boxShadow: shadow,
          overflow: "hidden",
        }}
      >
        {/* 播放器画布 */}
        <video
          id={id}
          width={width}
          height={height}
          muted
          loop
          ref={audioRef}
          onDoubleClick={() => {
            videoHandleClick();
          }}
          onClick={() => {
            videoHandleClick();
          }}
        >
          <source src={url} type="video/mp4"></source>
        </video>

        {/* 播放器控件 */}
        {control ? (
          <div className="nh_video_control_wrap">
            <div></div>
            <div className="right_box">
              <ElasticSlider
                className="volume_slider"
                defaultValue={defaultVolume}
                leftIcon={
                  <>
                    {defaultVolume !== 0 ? (
                      <Volume2
                        size={16}
                        style={{
                          position: "relative",
                          top: 2,
                          cursor: "pointer",
                        }}
                        onClick={() => {
                          muteClick();
                        }}
                      />
                    ) : (
                      <VolumeX
                        size={16}
                        style={{
                          position: "relative",
                          top: 2,
                        }}
                      />
                    )}
                  </>
                }
                rightIcon={<></>}
                isStepped
                stepSize={1}
                valueChange={volumeChange}
              />
              <div className="action_box">
                <div className="action_item_box" onClick={toggleFullScreen}>
                  {isFullScreen ? (
                    <Fullscreen size={20} />
                  ) : (
                    <Maximize size={20} />
                  )}
                </div>
              </div>
            </div>
          </div>
        ) : null}
      </div>
    </>
  );
};

export default NHVideo;
